package com.bluexmicro.ota2.picker.file

import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContract
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.ui.Modifier
import com.bluexmicro.ota2.picker.file.FilePickerActivity.Companion.PARAM_EXTENSION
import com.bluexmicro.ota2.picker.file.FilePickerActivity.Companion.RESULT_SELECTED_FILE
import com.bluexmicro.ota2.ui.theme.OtalibraryTheme
import com.livsdesign.picker.file.FilePicker
import java.io.File
import java.io.FileFilter

class FilePickerActivity : ComponentActivity() {


    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val ext = intent.getStringExtra(PARAM_EXTENSION) ?: "zip"
        val filter = FileFilter {
            if (it.isHidden || it.startsWith(".")) {
                return@FileFilter false
            }
            if (it.isDirectory) {
                return@FileFilter true
            }
            return@FileFilter listOf(ext)
                .map { ext -> ext.lowercase() }
                .contains(it.extension.lowercase())
        }
        setContent {
            OtalibraryTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
                ) {
                    Scaffold(
                        modifier = Modifier.fillMaxSize(),
                        topBar = {
                            TopAppBar(title = {
                                Text(text = "选择文件")
                            }, colors = TopAppBarDefaults.smallTopAppBarColors(
                                containerColor = MaterialTheme.colorScheme.primary,
                                titleContentColor = MaterialTheme.colorScheme.onPrimary,
                                navigationIconContentColor = MaterialTheme.colorScheme.onPrimary
                            ), navigationIcon = {
                                IconButton(onClick = { finish() }) {
                                    Icon(
                                        imageVector = Icons.Default.ArrowBack,
                                        contentDescription = null
                                    )
                                }
                            })
                        }
                    ) {
                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(it)
                        ) {
                            FilePicker(
                                filter,
                                onSelected = { file ->
                                    if (file == null) {
                                        setResult(RESULT_CANCELED)
                                    } else {
                                        val intent = Intent().apply {
                                            putExtra(RESULT_SELECTED_FILE, file)
                                        }
                                        setResult(RESULT_OK, intent)
                                    }
                                    finish()
                                }
                            )
                        }
                    }
                }
            }
        }
    }

    companion object {
        const val PARAM_EXTENSION = "extension"
        const val RESULT_SELECTED_FILE = "selectedFile"
    }

}

class LaunchFilePicker : ActivityResultContract<String, File?>() {

    override fun createIntent(context: Context, input: String): Intent {
        return Intent(context, FilePickerActivity::class.java).apply {
            putExtra(PARAM_EXTENSION, input)
        }
    }

    override fun parseResult(resultCode: Int, intent: Intent?): File? {
        return if (resultCode == RESULT_OK && intent != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getSerializableExtra(RESULT_SELECTED_FILE, File::class.java)
            } else {
                intent.getSerializableExtra(RESULT_SELECTED_FILE) as File?
            }
        } else {
            null
        }
    }

}